package org.budo.jedis.pool.factory;

import org.budo.jedis.pool.BudoJedisPool;
import org.budo.jedis.pool.util.BudoJedisPoolUtil;
import org.budo.support.lang.util.NumberUtil;
import org.springframework.beans.factory.FactoryBean;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;

/**
 * @author lmw
 */
@Slf4j
@Getter
@Setter
@Accessors(chain = true)
public class BudoJedisPoolFactory implements FactoryBean<BudoJedisPool> {
    private JedisPoolConfig jedisPoolConfig;

    private String host;

    private String password;

    private int port = Protocol.DEFAULT_PORT;

    private int timeout = Protocol.DEFAULT_TIMEOUT;

    private int database = Protocol.DEFAULT_DATABASE;

    public void setDbIndex(Integer dbIndex) {
        this.setDatabase(dbIndex);
    }

    @Override
    public Class<?> getObjectType() {
        return BudoJedisPool.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public BudoJedisPool getObject() throws Exception {
        return this.budoJedisPool();
    }

    public BudoJedisPool budoJedisPool() {
        return budoJedisPool_2(this.getHost(), //
                this.getPort(), //
                this.getPassword(), //
                this.getDatabase(), //
                this.getTimeout(), //
                this.getJedisPoolConfig());
    }

    public static BudoJedisPool budoJedisPool_1(String host, Integer port, String password) {
        return budoJedisPool_2(host, port, password, Protocol.DEFAULT_DATABASE, Protocol.DEFAULT_TIMEOUT, null);
    }

    private static BudoJedisPool budoJedisPool_2(String host, Integer port, String password, Integer database, Integer timeout, JedisPoolConfig jedisPoolConfig) {
        if (null == host || host.trim().isEmpty() || host.startsWith("${")) {
            throw new IllegalArgumentException("#12 host is required, host=" + host);
        }

        if ("N/A".equals(host)) {
            log.warn("#67 budoJedisPool_2, return null, host=" + host);
            return null;
        }

        if (null == jedisPoolConfig) {
            jedisPoolConfig = BudoJedisPoolUtil.defaultJedisPoolConfig();
        }

        String _host = host;
        Integer _port = port;
        if (_host.contains(",")) {
            _host = _host.split(",")[0];

            log.warn("#78 host = " + host + " > " + _host);
        }

        if (_host.contains(":")) {
            String[] split = _host.split(":");
            _host = split[0];
            _port = NumberUtil.toInteger(split[1]);

            log.warn("#78 host = " + host + " > " + _host + ", port=" + port + " > " + _port);
        }

        return new BudoJedisPool(jedisPoolConfig, //
                _host, //
                _port, //
                timeout, //
                password, //
                database);
    }
}
